import javax.jms.*;
import javax.naming.*;
import java.io.Serializable;

public class Noss implements Resource, Serializable {
	
    private Context jndiContext = null;
    private ConnectionFactory connectionFactory = null;
    private Destination dest = null;
    private Connection connection = null;
    private MessageProducer producer = null;
    private Session session;
    private static final String QUEUENAME = "C4ToNossQueue";
	
	public Noss() {
		/*
	     * Create a JNDI API InitialContext object if none exists
	     * yet.
	     */
		try {
            jndiContext = new InitialContext();
        } catch (NamingException e) {
            System.out.println("Could not create JNDI API context: " +
                e.toString());
            	e.printStackTrace(System.out);
            System.exit(1);
        }
        
        

        /*
         * Look up connection factory and destination.  If either
         * does not exist, exit.  If you look up a
         * TopicConnectionFactory or a QueueConnectionFactory,
         * program behavior is the same.
         */
        try {
            connectionFactory = (ConnectionFactory) jndiContext.lookup(
                    "jms/ConnectionFactory");
            dest = (Destination) jndiContext.lookup(QUEUENAME);
            System.out.println("Starting " + QUEUENAME + " Message Sender");
        } 
        catch (Exception e) {
            System.out.println("JNDI API lookup failed: " + e.toString());
            e.printStackTrace();
            System.exit(1);
        }

        /*
         * Create connection.
         * Create session from connection; false means session is
         * not transacted.
         * Create producer and text message.
         * Send messages, varying text slightly.
         * Send end-of-messages message.
         * Finally, close connection.
         */
        
        try {
            connection = connectionFactory.createConnection("guest","guest");

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(dest);
        }
        catch (JMSException e) {
            System.out.println("Exception occurred: " + e.toString());
        }
	}
        
    public void sendMessage(String msg) {
    	try {
	    	TextMessage message = session.createTextMessage();
	
	        
            message.setText(msg);
            System.out.println("Sending message: " + message.getText());
            producer.send(message);
            
            /*
	         * Send a non-text control message indicating end of
	         * messages.
	         */
            producer.send(session.createMessage());
        } 
    	catch (JMSException e) {
    		System.out.println("Exception occurred: " + e.toString());
    	}
    }
}
